const router = require('koa-router')() // 一边导入一边实例化
// const result = require('../../config/result.js')
// const { regcheck, checking } = require('../../config/checking.js')
const fs = require('fs');
const axios = require('axios');
// 操作数据库的接口
const { getToken, DownloadFileUrl } = require('../../config/databaseapi.js')
// 注册接口
router.post('/downloadfileorfolder', async (ctx) => {
  let { file_id, fileName } = ctx.request.body;
  console.log("调用下载单个文件/文件夹接口");
  // console.log(fileName,file_id);
  let file_list = [];
  let obj = { "fileid": file_id, "max_age": 7200 };
  file_list.push(obj);
  let res = await new getToken().posteve4(DownloadFileUrl, file_list);
  // console.log('下载结果', res);
  if (res.file_list[0].status === 0) {
    const fileUrl = res.file_list[0].download_url;
    // console.log(fileUrl);
    try {
      ctx.set('Content-Disposition', `attachment; filename="${encodeURI(fileName)}"`);
      const response = await axios.get(fileUrl, { responseType: 'stream' });
      // console.log(response.data);
      ctx.body = response.data;
    } catch (err) {
      ctx.body = { msg: '接收下载地址成功,下载失败', status: 0 }
    }
  } else {
    ctx.body = { msg: '接收下载地址失败', status: 0 }
  }
});

module.exports = router.routes()